import React, { useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';

import { changeCity, getCityList } from '../redux/action/CityActionCreator';
import { clearCinemaList } from '../redux/action/CinemaActionCreator';
import { useAutoHandleTabbar } from '../hooks/useTabbar';

const useCityList = (props) => {
  const { list, getCityList } = props;

  useEffect(() => {
    list.length === 0 && getCityList();
    return () => {};
  }, [list.length, getCityList]);
  return {
    list,
  };
};

const useHandeleClick = (props) => {
  const navigate = useNavigate();

  let { changeCity, clearCinemaList } = props;
  const handleClick = useCallback(
    (city) => {
      let { cityId: id, name } = city;

      // 切换城市
      changeCity({ id, name });
      // 清空影院缓存
      clearCinemaList();
      navigate('/cinema');
    },
    [navigate, changeCity, clearCinemaList]
  );
  return { handleClick };
};

const City = (props) => {
  useAutoHandleTabbar();
  const { list } = useCityList(props);
  const { handleClick } = useHandeleClick(props);

  return (
    <div>
      <ul>
        {list.map((item) => (
          <li
            key={item.cityId}
            onClick={() => handleClick(item)}>
            {item.name}
          </li>
        ))}
      </ul>
    </div>
  );
};

const MapStateToPropsParam = (state) => {
  return {
    list: state.CityReducer.cityList,
  };
};

const MapDispatchToPropsParam = {
  getCityList,
  changeCity,
  clearCinemaList,
};

export default connect(MapStateToPropsParam, MapDispatchToPropsParam)(City);
